package com.niodata.dp.monitor.common.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class TemplateUtil {

  private static Map<String, String> templateMap;
  private static Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);

  static {
    templateMap = new HashMap<>();

    try {
      cfg = new Configuration(Configuration.VERSION_2_3_23);
      cfg.setDefaultEncoding("UTF-8");
      StringTemplateLoader stringLoader = new StringTemplateLoader();
      PathMatchingResourcePatternResolver resourceLoader =
            new PathMatchingResourcePatternResolver();
      Resource[] resources =
            resourceLoader.getResources("classpath*:template/*.template");
      for (Resource resource : resources) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(resource.getInputStream(), output);
        String template = new String(output.toByteArray());
        stringLoader.putTemplate(
              resource.getFilename().substring(0, resource.getFilename().lastIndexOf(".")),
              template);
      }
      cfg.setTemplateLoader(stringLoader);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static String genMsgByTemplate(String templateKey, Map<Object, Object> data)
        throws IOException, TemplateException {
    Template template = cfg.getTemplate(templateKey);
    StringWriter writer = new StringWriter();
    template.process(data, writer);
    String msg = writer.toString();
    writer.close();
    return msg;
  }

}
